import base64
import urllib
import requests
import pathlib
import json
import config.globalVariable as Gv

API_KEY = "tn6eWFyTqw2SZUpyBszytWhp"
SECRET_KEY = "SVzGpUveLvqjEOE8D224DoXXblNyk4Vc"

def main(text):
    if text is None or len(text)<=0:
        return
    url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate?access_token=" + get_access_token()

    jsonfileaddr = pathlib.Path(__file__).parent.parent.parent.resolve().as_posix() + '/' + Gv.pngfileaddr
    # image 可以通过 get_file_content_as_base64("C:\fakepath\screenshot.png",True) 方法获取
    image = get_file_content_as_base64(jsonfileaddr, True)
    payload = 'image='+image+'&language_type=CHN_ENG&detect_direction=false&vertexes_location=true&paragraph=false&probability=false'
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    if response.status_code != 200:
        return
    data = json.loads(response.text)
    error_code = data.get('error_code')
    if error_code is not None:
        print(data.get('error_msg'))
        return
    for item in data.get('words_result'):
        words = item.get('words')
        if words is None or words.find(text) == -1:
            continue
        location =  item.get('location')
        print(location)
        return location


def get_file_content_as_base64(path, urlencoded=False):
    """
    获取文件base64编码
    :param path: 文件路径
    :param urlencoded: 是否对结果进行urlencoded
    :return: base64编码信息
    """
    with open(path, "rb") as f:
        content = base64.b64encode(f.read()).decode("utf8")
        if urlencoded:
            content = urllib.parse.quote_plus(content)
    return content


def get_access_token():
    """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    return str(requests.post(url, params=params).json().get("access_token"))


if __name__ == '__main__':
    p = main('标记股票')
    print(p)

if __name__ == '__main__':
    main()
